<?php

namespace app\task\controller;

use app\task\logic\DealHolidayLogic;

/**
 * 处理当天日期节假日信息
 * Created by PhpStorm.
 * User: tyll
 * Date: 2019/11/20
 * Time: 15:22.
 */
class DealHoliday extends Base
{
    public function __construct()
    {
        parent::__construct();
        $this->dh_logic = new DealHolidayLogic();
    }

    /**
     * 处理节假日信息.
     *
     * @return \think\response\Json
     */
    public function deal_holiday()
    {
        $year = date('Y');

        $maps = [];
        $h_detail = model('holiday')->get_detail($maps, 'now_date', 'now_date desc');
        $now_date = !empty($h_detail) ? $h_detail['now_date'] : '2020-01-01';
        $now_year = date('Y', strtotime($now_date));
        if ($year == $now_year) {
            return json($this->dh_logic->get_response(1, '处理节假日信息，当前年份已处理'));
        }

        $h = new \app\common\controller\Holiday();
        for ($m = 1; $m <= 12; ++$m) {
            $year_month = $year . '-' . $m;

            $holiday_arr = $h->deal_date_holiday($year_month);
            if ($holiday_arr === 0) {
                return json($this->dh_logic->get_response(0, '无对应参数的数据返回'));
            }

            $holiday_arr_new = [];
            foreach ($holiday_arr as $k => $v) {
                $holiday_arr_new[$k]['list'] = $v['list'];
            }

            $temp_arr = [];
            foreach ($holiday_arr_new as $k_1 => $v_1) {
                foreach ($v_1['list'] as $k_2 => $v_2) {
                    $temp_arr[$v_2['date']] = $v_2['status'];
                }
            }

            $day = date('t', strtotime($year_month));
            for ($d = 1; $d <= $day; ++$d) {
                $year_month_day = $year_month . '-' . $d;

                if (array_key_exists($year_month_day, $temp_arr)) {
                    if ($temp_arr[$year_month_day] == 1) {
                        $holiday = 1;
                    } elseif ($temp_arr[$year_month_day] == 2) {
                        $holiday = 0;
                    }
                } else {
                    $w = date('w', strtotime($year_month_day));
                    if ($w >= 1 && $w <= 5) {
                        $holiday = 0;
                    } else {
                        $holiday = 1;
                    }
                }

                $maps = [];
                $maps[] = ['now_date', '=', $year_month_day];
                $h_detail = model('holiday')->get_detail($maps, 'id');
                if (empty($h_detail)) {
                    $h_data = [];
                    $h_data['now_date'] = $year_month_day;
                    $h_data['holiday'] = $holiday;
                    $r = model('holiday')->insert($h_data);
                }
            }
        }

        return json($this->dh_logic->get_response(1, '处理节假日信息成功，年份：' . $year));
    }
}
